﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using MVVMComun;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Microsoft.Phone.Net.NetworkInformation;


namespace GuiaCiudad.ViewModel
{
   public class GuiaCiudadViewModel:NotificationObject  
    {
        GuiaCiudadModel GCM;

        private ObservableCollection<Foto> fotos;
        public ObservableCollection<Foto> Fotos  
        {
            get { return fotos; }
            set { fotos = value;
                OnPropertyChanged(this);
            }
        }

        private ObservableCollection<Noticia> noticias;
        public ObservableCollection<Noticia> Noticias
        {
            get { return noticias; }
            set { noticias = value;
                  OnPropertyChanged(this);
            }
        }

        private ObservableCollection<Pronostico> pronosticos;
        public ObservableCollection<Pronostico> Pronosticos
        {
            get { return pronosticos; }
            set { pronosticos = value;
                    OnPropertyChanged(this);
            }
        }

        private ActionComand saveCommand;

        public ActionComand SaveCommand
        {
            get {

                if (saveCommand == null)
                    saveCommand = new ActionComand(new Action(guardar));
                return   saveCommand; 
            
            }
           
        }


        private string ciudad;

        public string Ciudad
        {
            get { return ciudad; }
            set { ciudad = value;
            OnPropertyChanged(this);
            }
        }

        private string pais;

        public string Pais
        {
            get { return pais; }
            set { pais = value;
            OnPropertyChanged(this);
            }
        }
        
        


        public GuiaCiudadViewModel()
        {
            
            Fotos = new ObservableCollection<Foto>();
            ConfigModels();
          
            LoadSettings();
          
           if ( !NetworkInterface.GetIsNetworkAvailable())
         
            {

                LoadOffline();  

            }else{
          
            configServices();
            cargarDatos();
        }
           
        }

        private  async Task LoadOffline()
        {

            try
            {

                var localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                var folderToSave = await localfolder.CreateFolderAsync("Noticias", Windows.Storage.CreationCollisionOption.OpenIfExists);
                var file = await folderToSave.GetFileAsync("Noticias.dat");
                DataContractSerializer ds = new DataContractSerializer(new List<Noticia>().GetType());
                var stream = await file.OpenStreamForReadAsync();
                var resultN = ds.ReadObject(stream) as List<Noticia>;
                stream.Close();
                Noticias = new ObservableCollection<Noticia>(resultN);

            }
            catch (Exception e)
            {
                
                throw;
            }


            try
            {
              var  localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
             var   folderToSave = await localfolder.CreateFolderAsync("Pronosticos", Windows.Storage.CreationCollisionOption.OpenIfExists);
              var  file = await folderToSave.GetFileAsync("Pronosticos.dat");

var                ds = new DataContractSerializer(new List<Pronostico>().GetType());

  var              stream = await file.OpenStreamForReadAsync();
                var resultP = ds.ReadObject(stream) as List<Pronostico>;
                Pronosticos = new ObservableCollection<Pronostico>(resultP);
                stream.Close();
            }
            catch (Exception e)
            {
                
                throw;
            }


            try
            {
             var   localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
             var   folderToSave = await localfolder.CreateFolderAsync("Fotos", Windows.Storage.CreationCollisionOption.OpenIfExists);
              var  file = await folderToSave.GetFileAsync("fotos.dat");

               var ds = new DataContractSerializer(new List<Foto>().GetType());

              var  stream = await file.OpenStreamForReadAsync();
                var resultF = ds.ReadObject(stream) as List<Foto>;

                foreach (Foto f in resultF)
                {

                    //f.Url =  folderToSave.Path+ f.Titulo + ".jpg";

                    file = await folderToSave.GetFileAsync(f.Id + ".jpg");
                    stream = await file.OpenStreamForReadAsync();
                    System.Windows.Media.Imaging.BitmapImage Bi = new System.Windows.Media.Imaging.BitmapImage();
                    Bi.SetSource(stream);

                    f.BitmapImageSource = Bi;

                }

                stream.Close();
                Fotos = new ObservableCollection<Foto>(resultF);
            }
            catch (Exception e)
            {
                
                throw;
            }
    

        }

        private void LoadSettings()
        {
            System.IO.IsolatedStorage.IsolatedStorageSettings settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("Pais")) 
            {
                GCM.Pais = settings["Pais"].ToString();
            }
            if (settings.Contains("Ciudad"))
            {
                GCM.Ciudad = settings["Ciudad"].ToString();
            }
            Ciudad = GCM.Ciudad;
            Pais = GCM.Pais;
            GCM.WeatherS.Pais = Pais;
            GCM.WeatherS.Ciudad = Ciudad;
        }

        private void UpdateSettings() 
        {
            System.IO.IsolatedStorage.IsolatedStorageSettings settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("Pais"))
            {
                settings["Pais"] = Pais; ;
            }
            else {
                settings.Add("Pais", Pais);

            }
            if (settings.Contains("Ciudad"))
            {
                settings["Ciudad"] = Ciudad; ;
            }
            else
            {
                settings.Add("Ciudad", Ciudad);

            }
        }

        private async void  configServices()
        {
            GCM.FlickerS.FlickerServiceResponseReady += (s, e) => {


                //pesistObjectGenerico(e.Result, "Datos", "FotosUrl.dat");
                //Fotos = new ObservableCollection<Foto>(e.Result);
               if(e.Result.Count>10)
                e.Result.RemoveRange(9, e.Result.Count - 10);
              
                var a=   pesistObjectFotos(e.Result, "Fotos", "fotos.dat");
        
            };


            GCM.BingS.BingNewsServiceResponseReady += (s, e) =>
            {

                Noticias = new ObservableCollection<Noticia>(e.Result);

                var a = pesistObjectGenerico(e.Result, "Noticias", "Noticias.dat", e.Result.GetType());

            };

            GCM.WeatherS.WeatherResponseReady += (s, e) =>
            {
                Pronosticos = new ObservableCollection<Pronostico>(e.Result);

                var a =  pesistObjectGenerico(e.Result, "Pronosticos", "Pronosticos.dat", e.Result.GetType());
    

            };
        
        


        }

        private async Task<int> pesistFoto(Foto o,string folder,string name) {

            try
            {

                var localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                if (folder != string.Empty)
                {
                    var folderToSave = await localfolder.CreateFolderAsync(folder, Windows.Storage.CreationCollisionOption.OpenIfExists);
                    var file = await folderToSave.CreateFileAsync(name, Windows.Storage.CreationCollisionOption.ReplaceExisting);
                    var stream = await file.OpenStreamForWriteAsync();
                    System.Net.WebClient wc = new System.Net.WebClient();

                    wc.OpenReadCompleted += async (obj, e) =>
                    {
                        try
                        {
                            await e.Result.CopyToAsync(stream);
                            stream.Flush();
                            stream.Close();
                            stream = await file.OpenStreamForReadAsync();
                            System.Windows.Media.Imaging.BitmapImage Bi = new System.Windows.Media.Imaging.BitmapImage();
                            Bi.SetSource(stream);

                            o.BitmapImageSource = Bi;
                            stream.Close();
                        }
                        catch (Exception ex)
                        {
                            
                            
                        }

                    };
                    wc.OpenReadAsync(new Uri(o.Url));



                    //System.Net.HttpWebRequest wr = System.Net.HttpWebRequest.CreateHttp(o.Url);
                    //System.Net.WebResponse response;
                    //wr.BeginGetResponse((r) => { response = r.AsyncState as System.Net.WebResponse;

                    //Stream sr=  response.GetResponseStream();

                    // sr.CopyTo(stream);



                    // stream.Close();


                    //}, wr);




                    //stream = await file.OpenStreamForReadAsync();


                    // var rr = xs.Deserialize(stream) as ObservableCollection<Foto>;

                    //  var  rr = ds.ReadObject(stream) as ObservableCollection<Foto>;

                    //System.Windows.Media.Imaging.BitmapImage Bi = new System.Windows.Media.Imaging.BitmapImage();
                    //Bi.SetSource(stream);


                    //stream.Close();

                    //var fielrr = await folderToSave.GetFilesAsync();

                    //await fielrr[0].DeleteAsync();

                    //await folderToSave.DeleteAsync();

                }
            }
            catch (Exception e)
            {
                
                
            }
               return 0;
 
        }



        private async Task<int> pesistObjectFotos(List<Foto> o, string folder, string name)
        { 

            var localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            if (folder != string.Empty)
            {
                var folderToSave = await localfolder.CreateFolderAsync(folder, Windows.Storage.CreationCollisionOption.OpenIfExists);


                var file = await folderToSave.CreateFileAsync(name, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                var stream = await file.OpenStreamForWriteAsync();

                DataContractSerializer ds = new DataContractSerializer(o.GetType());
                ds.WriteObject(stream,o);
                stream.Close();
            


            foreach (Foto f in o) {
                try
                {
                    await pesistFoto(f, "Fotos", f.Id + ".jpg");

                   // file = await folderToSave.GetFileAsync(f.Titulo + ".jpg");
                    //stream = await file.OpenStreamForReadAsync();
                    //System.Windows.Media.Imaging.BitmapImage Bi = new System.Windows.Media.Imaging.BitmapImage();
                    //Bi.SetSource(stream);
                   
                    //f.BitmapImageSource = Bi;  
                    //stream.Close();
                
                }
                catch(Exception e) { 
                
                }
            }
            }
            Fotos = new ObservableCollection<Foto>(o);
            return 0;
        }


        private async Task<int> pesistObjectGenerico(object o, string folder, string name, Type type)
        {

            var localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            if (folder != string.Empty)
            {
               
                var folderToSave = await localfolder.CreateFolderAsync(folder, Windows.Storage.CreationCollisionOption.OpenIfExists);
              
                var file = await folderToSave.CreateFileAsync(name, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                var stream = await file.OpenStreamForWriteAsync();

                DataContractSerializer ds = new DataContractSerializer(type);
                ds.WriteObject(stream, o);
                stream.Close();
            }
            return 0;
        }

        

        private void cargarDatos()
        {
           // GCM.FlickerS.Size = "s";
            GCM.FlickerS.getFotos(GCM.Ciudad);
            GCM.BingS.getNoticias(GCM.Ciudad);
            GCM.WeatherS.getForeCast();


            if (System.ComponentModel.DesignerProperties.IsInDesignTool) {
                Noticias = new ObservableCollection<Noticia>() {new Noticia(){Titulo="Noticia1",Fuente="Fuente01",Descripcion="Resumen"} };

                Pronosticos = new ObservableCollection<Pronostico>() { new Pronostico(){ TempC = "28",TempF="78", Condicion="Nuboso,con posibilidades de lluvia",Dia="Sabado",AltaF="90",AltaC="32",BajaF="78",BajaC="22" },
                                                                                            new Pronostico(){ TempC = "28",TempF="78", Condicion="Soleado,todo bien",Dia="Domingo",AltaF="80",AltaC="30",BajaF="68",BajaC="20" }};
            }

        }

        private void ConfigModels()
        {
            GCM = new GuiaCiudadModel();
        }

        private void guardar() {


            if (NetworkInterface.GetIsNetworkAvailable())
            {

                if (Ciudad != GCM.Ciudad)
                {
                    UpdateSettings();
                    GCM.Pais = Pais;
                    GCM.Ciudad = Ciudad;
                    GCM.WeatherS.Pais = Pais;
                    GCM.WeatherS.Ciudad = Ciudad;
                    configServices();
                    cargarDatos();

                }
            }
            
        
        } 
   
   }

    

}
